<!--
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 -->

<div class="chat-container">
  <!-- Sidebar with conversation list -->
  <div class="chat-sidebar" [class.collapsed]="sidebarCollapsed">
    <div class="sidebar-header">
      <h3>{{ 'menu.extras.ai.chat' | i18n }}</h3>
      <button nz-button nzType="primary" nzSize="small" (click)="createNewConversation()" [nzLoading]="isLoading">
        <i nz-icon nzType="plus"></i>
        New Chat
      </button>
    </div>

    <div class="conversation-list">
      <div
        *ngFor="let conversation of conversations"
        class="conversation-item"
        [class.active]="currentConversation?.conversationId === conversation.conversationId"
        (click)="selectConversation(conversation)"
      >
        <div class="conversation-content">
          <div class="conversation-title">
            {{ getConversationTitle(conversation) }}
          </div>
          <div class="conversation-time">
            {{ conversation.updatedAt | date : 'MMM d, HH:mm' }}
          </div>
        </div>
        <button nz-button nzType="text" nzSize="small" nzDanger (click)="deleteConversation(conversation, $event)" class="delete-btn">
          <i nz-icon nzType="delete"></i>
        </button>
      </div>
    </div>
  </div>

  <!-- Main chat area -->
  <div class="chat-main">
    <!-- Header -->
    <div class="chat-header">
      <button nz-button nzType="text" (click)="toggleSidebar()" class="sidebar-toggle">
        <i nz-icon [nzType]="sidebarCollapsed ? 'menu-unfold' : 'menu-fold'"></i>
      </button>

      <div class="chat-title">
        <h2 *ngIf="currentConversation">
          {{ getConversationTitle(currentConversation) }}
        </h2>
        <h2 *ngIf="!currentConversation"> HertzBeat AI Agent </h2>
      </div>
    </div>

    <!-- Messages area -->
    <div class="messages-container" #messagesContainer>
      <!-- Loading indicator -->
      <div *ngIf="isLoading" class="loading-container">
        <nz-spin nzSimple [nzSize]="'large'">
          <ng-template #indicator>
            <i nz-icon nzType="loading" nzSpin></i>
          </ng-template>
        </nz-spin>
        <p>Loading conversation history...</p>
      </div>

      <!-- Welcome message -->
      <div *ngIf="messages.length === 0 && !isLoading" class="welcome-message">
        <div class="welcome-content">
          <img [src]="theme === 'dark' ? 'assets/logo_white.svg' : 'assets/logo.svg'" alt="HertzBeat Logo" class="welcome-icon" />
          <h3>Welcome to HertzBeat AI Agent!</h3>
          <p>
            I'm your intelligent monitoring companion, ready to help you manage and optimize your infrastructure monitoring. You can ask me
            to:
          </p>
          <ul>
            <li>🔍 Query and manage monitors by status, type, or labels</li>
            <li>➕ Add new monitors for websites, APIs, databases, and services</li>
            <li>🚨 View and analyze alerts with comprehensive filtering</li>
            <li>📊 Access real-time and historical metrics data</li>
            <li>⚙️ Configure alert rules and thresholds</li>
            <li>⚡ Troubleshoot performance issues across your infrastructure</li>
          </ul>
          <p>Ask me anything about your monitoring setup!</p>
        </div>
      </div>

      <!-- Chat messages -->
      <div *ngFor="let message of messages; let i = index" class="message" [class.user-message]="message.role === 'user'">
        <div class="message-avatar">
          <i nz-icon [nzType]="message.role === 'user' ? 'user' : 'robot'"></i>
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="message-role">{{ message.role === 'user' ? 'You' : 'AI Assistant' }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            <span *ngIf="message.role === 'assistant' && isLoading && i === messages.length - 1" class="streaming-indicator">
              <nz-spin nzSize="small"></nz-spin>
            </span>
          </div>
          <div class="message-text" [innerHTML]="message.content"></div>
          <div *ngIf="message.role === 'assistant' && message.content === '' && isLoading" class="typing-indicator">
            <nz-spin nzSize="small"></nz-spin>
            <span>Starting to type...</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Input area -->
    <div class="input-area">
      <div class="input-container">
        <nz-textarea-count [nzMaxCharacterCount]="1000">
          <textarea
            nz-input
            [(ngModel)]="newMessage"
            (keypress)="onKeyPress($event)"
            [disabled]="isLoading"
            placeholder="Ask me anything about monitoring..."
            rows="3"
            style="resize: none"
          ></textarea>
        </nz-textarea-count>
        <button
          nz-button
          nzType="primary"
          (click)="sendMessage()"
          [disabled]="!newMessage.trim() || isLoading"
          [nzLoading]="isLoading"
          class="send-button"
        >
          <i nz-icon nzType="send"></i>
        </button>
      </div>
      <div class="input-hint">
        <small>Press Enter to send, Shift+Enter for new line</small>
        <button nz-button nzType="link" nzSize="small" (click)="onShowConfigModal()" style="float: right">
          <i nz-icon nzType="setting"></i>
          Modify API Key
        </button>
      </div>
    </div>
  </div>
</div>

<!-- OpenAI Configuration Modal -->
<nz-modal
  [(nzVisible)]="showConfigModal"
  nzTitle="OpenAI Configuration"
  (nzOnCancel)="onCloseConfigModal()"
  (nzOnOk)="onSaveOpenAiConfig()"
  nzMaskClosable="false"
  [nzClosable]="false"
  nzWidth="600px"
  [nzOkLoading]="configLoading"
  nzOkText="Validate & Save"
  nzCancelText="Cancel"
>
  <div *nzModalContent class="-inner-content">
    <form nz-form nzLayout="vertical">
      <nz-form-item>
        <nz-form-label nzRequired="true">OpenAI API Key</nz-form-label>
        <nz-form-control nzErrorTip="API Key is required">
          <input nz-input [(ngModel)]="openAiConfig.apiKey" name="apiKey" type="password" placeholder="sk-..." required />
          <p class="form-help">Your OpenAI API key (starts with sk-). The key will be validated when saved.</p>
        </nz-form-control>
      </nz-form-item>
    </form>
  </div>
</nz-modal>
